package triFileSystem;

import transaction.Transaction;
import triStorage.*;
import utils.Constants;
import utils.Converter;

public class PageReader implements IReader {

	private int pageId;
	private int pos;
	private TriMMPFile mmpfile;
	
	public PageReader(int pageId, TriMMPFile mmpfile) {
		this.pos = 0;
		this.pageId = pageId;
		this.mmpfile = mmpfile;
	}
	
	@Override
	public Integer readInt() {
		Integer value = mmpfile.readInt(pageId, pos);
		pos += Constants.INT_SIZE;
		
		return value;
	}

	@Override
	public Long readLong() {
		Long value = mmpfile.readLong(pageId, pos);
		pos += Constants.LONG_SIZE;
		
		return value;
	}

	@Override
	public String readString() {
		Integer len = readInt();
			
		if (len == null || len < 0)
			return null;
		else if (len == 0)
			return "";
			
		byte[] bytes = new byte[len];
		mmpfile.readBytes(pageId, pos, bytes, 0, len);
		pos += len;
			
		return Converter.Bytes2String(bytes, 0);
	}

	@Override
	public void skipString() {
		Integer len = readInt();
		if (len == null || len <= 0)
			return ;
		
		pos += len;
	}

	@Override
	public long getReadPos() {
		return mmpfile.PAGE_SIZE * pageId + pos;
	}

	@Override
	public IWriter toWriter(Transaction tx) {
		return new PageWriter(pageId, mmpfile);
	}

	@Override
	public void dispose() {
		
	}

	@Override
	public void seek(long readPos) {
		pageId = (int)((readPos - 1) / mmpfile.PAGE_SIZE);
		pos = (int)((readPos - 1) % mmpfile.PAGE_SIZE) + 1;
	}

}
